<template>
    <div class="employee-management">
        <!-- 页面标题 -->
        <div class="page-title">
            <h2>员工管理</h2>
        </div>
        <el-divider />

        <!-- 搜索与操作区 -->
        <div class="operation-bar">
            <el-input v-model="searchKeyword" placeholder="输入姓名/手机号查询" clearable
                style="width: 220px; margin-right: 15px" @keyup.enter="handleSearch" />
            <el-button   :dark="false" color="rgb(35, 198, 200)" @click="handleSearch" plain>查询</el-button>
            
            <el-button   :dark="false"  color="rgb(35, 198, 200)" @click="openAddForm" plain>
                <el-icon>
                    <Plus />
                </el-icon> 新增员工
            </el-button>
        </div>

        <!-- 员工列表表格 -->
        <el-table :data="filteredEmployees" border stripe style="width: 100%; margin-top: 15px"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="name" label="姓名" align="center" />
            <el-table-column prop="position" label="职务" align="center" />
            <el-table-column prop="gender" label="性别" width="80" align="center" />
            <el-table-column prop="phone" label="手机号" align="center" />
            <el-table-column prop="idCard" label="身份证号" align="center" />

            <el-table-column prop="brand" label="负责品牌" align="center" />
            <el-table-column label="品牌门店" align="center">
                <template #default="scope">
                    <el-popover placement="right" :width="400" trigger="click">
                        <template #reference>
                            <!-- <el-button style="margin-right: 16px">点击查看</el-button> -->
                            <el-link type="primary">点击查看</el-link>
                        </template>
                        <h3> 门店列表</h3>

                        <ul>
                            <li> 1.泰州-陈佳美容</li>
                            <li>2.南京-克丽缇娜</li>
                            <li>2.南京-克丽缇娜</li>
                            <li>2.南京-克丽缇娜</li>
                        </ul>
                    </el-popover>
                </template>
            </el-table-column>
            <!-- <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleDetail(scope.row)">查看</el-button>
          <el-button size="mini" type="warning" @click="openEditForm(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
</el-table-column> -->
            <el-table-column label="操作" align="center" width="579">
                <template #default="scope">
                    <el-button size="mini" @click="handleClock(scope.row)" color="rgb(237, 85, 101)" :dark="false"
                        plain>打卡管理</el-button>
                    <el-button size="mini" @click="handleReport(scope.row)" color="rgb(35, 198, 200)" :dark="false"
                        plain>工作报表</el-button>
                    <el-button size="mini" @click="openEditForm(scope.row)" color=" rgb(248, 172, 89)" :dark="false"
                        plain>修改信息</el-button>
                    <el-button size="mini" @click="handleSalary(scope.row)" color="rgb(237, 85, 101)" :dark="false"
                        plain>薪资</el-button>
                    <el-button size="mini" @click="handleDelete(scope.row)" color="rgb(237, 85, 101)" :dark="false"
                        plain>删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 批量操作区 -->
        <div class="batch-operation" v-if="selectedRows.length > 0">
            <el-button type="danger" @click="batchDelete">
                <el-icon>
                    <Delete />
                </el-icon> 批量删除（{{ selectedRows.length }}条）
            </el-button>
        </div>

        <!-- 新增/编辑表单弹窗 -->
        <el-dialog v-model="formVisible" :title="isEdit ? '编辑员工' : '新增员工'" width="600px" destroy-on-close>
            <el-form ref="employeeForm" :model="formData" :rules="formRules" label-width="100px" class="employee-form">
                <el-form-item label="员工编号" prop="employeeId" v-if="isEdit">
                    <el-input v-model="formData.employeeId" disabled />
                </el-form-item>

                <el-form-item label="姓名" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入员工姓名" />
                </el-form-item>

                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="formData.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入手机号" />
                </el-form-item>

                <el-form-item label="身份证号" prop="idCard">
                    <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
                </el-form-item>

                <el-form-item label="职务" prop="position">
                    <el-select v-model="formData.position" placeholder="请选择职务">
                        <el-option label="总经理" value="总经理" />
                        <el-option label="区域经理" value="区域经理" />
                        <el-option label="店长" value="店长" />
                        <el-option label="美容导师" value="美容导师" />
                        <el-option label="库管员" value="库管员" />
                        <el-option label="收银员" value="收银员" />
                    </el-select>
                </el-form-item>

                <el-form-item label="负责品牌" prop="brand">
                    <el-checkbox-group v-model="formData.brand">
                        <el-checkbox label="雅诗兰黛" />
                        <el-checkbox label="兰蔻" />
                        <el-checkbox label="迪奥" />
                        <el-checkbox label="香奈儿" />
                        <el-checkbox label="阿玛尼" />
                        <el-checkbox label="YSL" />
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item label="基本薪资" prop="baseSalary">
                    <el-input v-model.number="formData.baseSalary" placeholder="请输入基本薪资" />
                </el-form-item>

                <el-form-item label="入职日期" prop="hireDate">
                    <el-date-picker v-model="formData.hireDate" type="date" placeholder="选择入职日期" style="width: 100%" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="formVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>


        <!-- 删除确认弹窗 -->
        <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px" :show-close="false">
            <p>确定要删除 <span class="text-danger">{{ deleteTargetName }}</span> 吗？</p>
            <template #footer>
                <el-button @click="deleteConfirmVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete">确定删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import { useRouter } from "vue-router";
// 员工数据
const employees = ref([]);
const filteredEmployees = ref([]);
const searchKeyword = ref('');
const selectedRows = ref([]);

// 表单相关
const formVisible = ref(false);
const isEdit = ref(false);
const employeeForm = ref(null);
const deleteConfirmVisible = ref(false);
const deleteTarget = ref(null);
const deleteTargetName = ref('');

const  router = useRouter() 

// 表单数据
const formData = reactive({
    id: '',
    employeeId: '',
    name: '',
    gender: '女',
    phone: '',
    idCard: '',
    position: '',
    brand: [],
    baseSalary: null,
    hireDate: ''
});

// 表单验证规则
const formRules = reactive({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: '请输入2-4位中文姓名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    idCard: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入18位身份证号', trigger: 'blur' }
    ],
    position: [
        { required: true, message: '请选择职务', trigger: 'change' }
    ],
    brand: [
        { required: true, message: '请至少选择一个负责品牌', trigger: 'change' }
    ],
    baseSalary: [
        { required: true, message: '请输入基本薪资', trigger: 'blur' },
        { type: 'number', min: 0, message: '薪资不能为负数', trigger: 'blur' }
    ],
    hireDate: [
        { required: true, message: '请选择入职日期', trigger: 'change' }
    ]
});

// 初始化数据
onMounted(() => {
    // 模拟后端数据
    employees.value = [
        {
            id: 1,
            employeeId: 'EMP2024001',
            name: '张敏',
            gender: '女',
            phone: '13812345678',
            idCard: '310101199001011234',
            position: '店长',
            brand: ['雅诗兰黛', '兰蔻'],
            baseSalary: 8000,
            hireDate: '2020-03-15'
        },
        {
            id: 2,
            employeeId: 'EMP2024002',
            name: '李强',
            gender: '男',
            phone: '13987654321',
            idCard: '110101199205067890',
            position: '区域经理',
            brand: ['迪奥', '香奈儿'],
            baseSalary: 12000,
            hireDate: '2018-07-20'
        },
        {
            id: 3,
            employeeId: 'EMP2024003',
            name: '王丽',
            gender: '女',
            phone: '13756789012',
            idCard: '440101199511123456',
            position: '美容导师',
            brand: ['阿玛尼', 'YSL'],
            baseSalary: 6500,
            hireDate: '2021-09-05'
        }
    ];
    filteredEmployees.value = [...employees.value];
});


//
const handleClock  = (row) => {
    router.push({ path: '/system/employeeManagement/clockIn', query: { employeeId: row.employeeId } });
    ElMessage.info(`打开 ${row.name} 的打卡管理`);

    // 实际项目中可打开打卡管理弹窗或页面
}; 


// 搜索功能
const handleSearch = () => {
    const keyword = searchKeyword.value.trim().toLowerCase();
    if (!keyword) {
        filteredEmployees.value = [...employees.value];
        return;
    }
    filteredEmployees.value = employees.value.filter(emp =>
        emp.name.toLowerCase().includes(keyword) ||
        emp.phone.includes(keyword)
    );
};

// 打开新增表单
const openAddForm = () => {
    isEdit.value = false;
    // 重置表单
    Object.keys(formData).forEach(key => {
        formData[key] = key === 'gender' ? '女' : (key === 'baseSalary' ? null : '');
    });
    formVisible.value = true;
};

// 打开编辑表单
const openEditForm = (row) => {
    isEdit.value = true;
    // 填充表单数据
    Object.assign(formData, { ...row });
    formVisible.value = true;
};

// 提交表单
const submitForm = () => {
    employeeForm.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 编辑操作
                const index = employees.value.findIndex(emp => emp.id === formData.id);
                if (index !== -1) {
                    employees.value[index] = { ...formData };
                    ElMessage.success('员工信息更新成功');
                }
            } else {
                // 新增操作
                const newId = employees.value.length > 0
                    ? Math.max(...employees.value.map(emp => emp.id)) + 1
                    : 1;
                const newEmp = {
                    ...formData,
                    id: newId,
                    employeeId: `EMP${new Date().getFullYear()}${String(newId).padStart(3, '0')}`
                };
                employees.value.push(newEmp);
                ElMessage.success('新员工添加成功');
            }
            // 刷新列表
            handleSearch();
            formVisible.value = false;
        }
    });
};

// 处理删除
const handleDelete = (row) => {
    deleteTarget.value = row;
    deleteTargetName.value = row.name;
    deleteConfirmVisible.value = true;
};
const handleSalary = () => {
    router.push("/system/employeeSalary")
}
// 确认删除
const confirmDelete = () => {
    employees.value = employees.value.filter(emp => emp.id !== deleteTarget.value.id);
    handleSearch(); // 刷新列表
    selectedRows.value = []; // 清空选中状态
    deleteConfirmVisible.value = false;
    ElMessage.success('删除成功');
};

// 批量删除
const batchDelete = () => {
    const ids = selectedRows.value.map(row => row.id);
    employees.value = employees.value.filter(emp => !ids.includes(emp.id));
    handleSearch();
    selectedRows.value = [];
    ElMessage.success(`已删除 ${ids.length} 条数据`);
};

// 选中行变化
const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
};

// 查看详情
const handleDetail = (row) => {
    ElMessage.info(`查看 ${row.name} 的详细信息`);
    // 实际项目中可打开详情弹窗
};

// 工作报表
const handleReport = (row) => {
    router.push({ path: '/system/employeeManagement/workreport', query: { employeeId: row.employeeId } });
    ElMessage.info(`查看 ${row.name} 的工作报表`);
    // 实际项目中可打开工作报表页面
};

</script>

<style scoped>
.employee-management {

    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.page-title {
    margin-bottom: 15px;
}

.page-title h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.operation-bar {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.batch-operation {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.employee-form {
    margin-top: 15px;
}

/* 调整复选框布局 */
:deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
}

.text-danger {
    color: #ff4d4f;
    font-weight: 500;
}
</style>